import secrets
from typing import List, Union, Dict, Any

from pydantic import BaseSettings, AnyHttpUrl, validator, root_validator


class Settings(BaseSettings):
    PROJECT_NAME: str
    SECRET_KEY: str = secrets.token_urlsafe(32)
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 120
    
    # CORS设置
    CORS_ORIGINS: List[str] = []

    @validator("CORS_ORIGINS", pre=True)
    def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
        if isinstance(v, str) and not v.startswith("["):
            return [i.strip() for i in v.split(",")]
        elif isinstance(v, (list, str)):
            return v
        raise ValueError(v)

    # 数据库设置
    DATABASE_URL: str
    
    # Redis设置
    REDIS_URL: str = "redis://:Redis_2025_ShipmentMonitor@localhost:6379"
    
    # Celery Redis设置 - 默认值将在root_validator中设置
    REDIS_BROKER_URL: str = ""
    REDIS_BACKEND_URL: str = ""
    
    @root_validator(pre=True)
    def set_redis_urls(cls, values):
        # 确保REDIS_URL存在
        if "REDIS_URL" in values:
            # 只有当没有明确设置REDIS_BROKER_URL时才设置它
            if not values.get("REDIS_BROKER_URL"):
                values["REDIS_BROKER_URL"] = values["REDIS_URL"] + "/0"
            
            # 只有当没有明确设置REDIS_BACKEND_URL时才设置它
            if not values.get("REDIS_BACKEND_URL"):
                values["REDIS_BACKEND_URL"] = values["REDIS_URL"] + "/1"
        return values
        
    class Config:
        case_sensitive = True
        env_file = ".env"


settings = Settings()